import React, { Component } from 'react'
import { Input, Button,Rate, Upload, Icon, Modal,message,Popconfirm } from 'antd';
import { connect } from 'react-redux'
import { actionCreators } from './store/index'
import { prefix } from '../../common/globalStyle'
import BBS from './components/bbs'
import RateCom from './components/rate'
import { withRouter,Link } from 'react-router-dom'
import api from '../../api/api'
import $ from  'jquery'
import Video from './components/video'
import { 
  LiveWrapper, 
  HeaderWrapper, 
  HeaderLeft, 
  LiveState,
  HeaderRight,
  AvatarWrapper,
  InfoWrapper,
  CourseWrapper,
  ListWrapper,
  ChatWrapper,
  ChatList,
  EnterWrapper,
  ContentWrapper,
  ContentTitle,
  Content,
  AbstractWrapper,
} from './style'

class Live extends Component {
  constructor(props) {
    super(props)
    this.state = {
      normal: true,
      chatList: [],
      onlineList: [],
      chat: '',
      userData: JSON.parse(localStorage.getItem('userData')),
      answerVisible: false,
      count: 0,
      answer: {
        img: '',
        text: ''
      },
      initEdit: false,
      url: '',
      next: false,
      messageType: 1,
      page: 1,
      pageSize: 15
    }
  }
  
  componentDidMount() {
    let roomId = this.getQueryStr('roomId')
    if(roomId) {
      this.props.getVideoItem({
        roomId
      })
      api.getVideoUrl({
        roomId
      }).then(res =>{
        if(res.code === 20000) {
          if(res.data.type === 'JoyActivity') {
            this.timeout = setTimeout(()=> {
              this.renderPay()
              this.initWebSocket()
            },300)
      
            this.timer = setInterval(()=> {
              // console.log('this.websock', this.websock)
              if(window.websock) {
                window.websock.send('hb');
              }else {
                this.initWebSocket()
              }
            }, 60000)
          }
        }
      })
    }
  }

  
  componentWillUnmount() {
    if(window.myVideo && this.props.video.get('type') === 'JoyActivity') {
      window.myVideo.dispose()
    }
    this.websocketclose()
    clearInterval(this.timer)
    clearTimeout(this.timeout)
  }

  // 滚动条
  changeScroll(chat) {
    if(chat) {
      chat.scrollTop = chat.scrollHeight
    }
  }

  // 直播页面
  renderLive() {
    const info = this.props.video ? this.props.video: {}
    // const user = JSON.parse(localStorage.getItem('userData'))
    return (
      <LiveWrapper>
        {this.renderHeader()}
        {/* 视频播放 */}
        <CourseWrapper>
          {/* <video style={{width: '1508px', height: '858px'}} src="//g.alicdn.com/de/prismplayer-flash/1.5.1/PrismPlayer.swf" controls="controls" > 
            您的浏览器不支持 video 标签
          </video> */}
          { this.state.normal ?  
          <div style={{width: '78%', float: 'left'}}>
            <video id="liveVideo" className="video-js vjs-default-skin vjs-big-play-centered" controls preload="auto" data-setup='{}' style={{width: '100%', height: '858px'}}>
                <source id="source" src={info.get('m3u8_lsd_url')} type="application/x-mpegURL"></source>
                {/* <source id="source" src='http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8' type="application/x-mpegURL"></source> */}
            </video> </div>: 
          <img alt="" src={this.state.url ? this.state.url : this.props.liveImg.get('url')} style={{width: '78%', height: '858px', float: 'left'}} />}
          <ListWrapper>
            <div style={{position: 'relative'}}>
            {
              this.state.normal ?  <img alt="" style={{width: '100%', height: '212px'}} src={this.state.url ? this.state.url : this.props.liveImg.get('url')}/> : 
              <div style={{width: '100%'}}>
                {/* <div id="live-video-pay" style={{width: '100%', height: '212px'}}></div> */}
                <video id="liveVideoNormal" className="video-js vjs-default-skin vjs-big-play-centered" controls preload="auto" data-setup='{}' style={{width: '100%', height: '212px'}}>
                  <source id="source" src={info.get('m3u8_lsd_url')} type="application/x-mpegURL"></source>
                </video>
              </div>
            }
              <div className="change-status" onClick={()=> this.changeStatus()}>
                <Icon type="swap" /> 切换
              </div>
            </div>
            <a href={this.props.downUrl} disabled={ this.props.downUrl? false: true} style={{color: this.props.downUrl?'#333': '#999'}}>
              <i className="iconfont icon-xiazai icon"></i>
              下载课件
            </a>
            <ChatWrapper>
              <p>聊天</p>
              <ChatList ref={(chat) => this.changeScroll(chat)}> 
                {
                  this.state.chatList.map((item,idx) => {
                    return <li key={idx}>
                      {
                        !item.isAll ? <p><span style={{color: '#8bca3'}}>
                        {item.username} @ {item.to}
                      </span>
                      :{item.message}</p> : <div>
                        {
                          item.status === 'system' ? <p style={{color: 'red'}}>{item.username}:{item.message}</p> : <p style={{color: '#fff'}}>{item.username}:{item.message}</p> 
                        }
                        </div>
                      }
                    </li>
                  })
                }
              </ChatList>
              <EnterWrapper>
                <Input placeholder="和大家一起聊天吧~" value={this.state.chat} onChange={(val)=>this.setState({chat: val.target.value})}/>
                <Button type="primary" onClick={this.websocketsend.bind(this)}>
                  发送
                </Button>
              </EnterWrapper>
            </ChatWrapper>
          </ListWrapper>
        </CourseWrapper>
        {/* 课程评分，提问，简介 */}
        <ContentWrapper>
          <RateCom {...this.props} showModal={()=> this.setState({visible: true})}  startAnswer={()=> this.changeAnswer()} />
          {/* 提问 */}
          <BBS {...this.props} getAllComment={(obj)=>this.getAllComment(obj)} type="live"/>
          {/* 简介 */}
          <AbstractWrapper>
            <ContentTitle>
              课程简介
            </ContentTitle>
            <Content>
              {info.get('description')}
            </Content>
          </AbstractWrapper>
        </ContentWrapper>
      </LiveWrapper>
    )
  }  
  
  changeStatus () {
    this.setState({normal:!this.state.normal}, ()=> this.renderPay())
  }

  // 确定评分
  handleRate() {
    this.props.addRate({
      id: this.props.video.get('lessonId'),
      star: this.state.rateValue,
      type: 1
    })
    this.setState({
      visible: false
    })
  }

  // 取消评分
  handleCancel() {
    this.setState({
      visible: false,
      answerVisible: false,
      next: false,
      count: 0
    })
  }

  nextWork() {
    let idx = this.state.count + 1 
    if(this.state.next) {
      this.setState({
        count: idx,
        next: (idx+1)< this.props.homeWork.size,
        answer: {
          text: this.props.homeWork.getIn([idx,'answer', 'text']),
          img: this.props.homeWork.getIn([idx,'answer', 'picUrl'])
        }
      }, ()=> {
        let text = this.props.homeWork.getIn([idx,'answer', 'text']) ? this.props.homeWork.getIn([idx,'answer', 'text']) : ''
        window.editor2.txt.html(text)
      })
    }
  }

  renderHeader() {
    const info = this.props.video ? this.props.video: {}
    const user = JSON.parse(localStorage.getItem('userData'))
    return (
      <HeaderWrapper>
        <HeaderLeft>
          <Link to="/" title="返回首页"><i className="iconfont icon-tuichu2 icon"></i></Link>
            <span>{info.get('name')}</span>
            {
              info.get('type') === 'LocalVideo' ? '' : <LiveState>正在直播</LiveState>
            }
        </HeaderLeft>
        <HeaderRight>
          <AvatarWrapper>
            <img alt="" src={info.get('teacherPhoto')}/>
            <span>{info.get('teacherName')}</span>
          </AvatarWrapper> 
          <InfoWrapper>
            <i className="iconfont icon-gerenxinxi icon"></i>
            <span>{user.name}</span>
            <span>{user.stuGradeStr}</span>
          </InfoWrapper>
        </HeaderRight>
      </HeaderWrapper>
    )
  }

  changeVideoStyle(video) {
    let w,h
    if(this.state.screen) {
      if(video) {
        w = this.state.clientWidth/2 + 'px'
        h = 858/1903*this.state.clientWidth/2 + 'px'
        video.style.width = w
        video.style.marginTop = '5px'
        video.style.height = h
      }
    }else {
      if(video) {
        w = 1500/1903*this.state.clientWidth + 'px'
        h = 858/1903*this.state.clientWidth + 'px'
        video.style.width = w
        video.style.height = h
      }
    }
  }

  changeBigImg(item) {
    this.setState({
      bigImg: item
    })
  }
  // 提交回答
  handleAnswer() {
    let text =  window.editor2.txt.html()
    let count = this.state.count
    let obj = this.state.answer
    obj.text = text
    if(!text && !obj.img) {
      message.error('练习内容不能为空')
      return 
    }
    this.props.saveHomeWork({
      text: text,
      pic: obj.img,
      homeworkId: this.props.homeWork.getIn([count,'homework', 'id'])
    })
    let idx = this.state.count + 1
    if(idx < this.props.homeWork.size) {
      this.setState({
        count: idx,
        answer: {
          text: this.props.homeWork.getIn([idx,'answer', 'text']),
          img: this.props.homeWork.getIn([idx,'answer', 'picUrl']),
        },
        next: (idx+1) === this.props.homeWork.size ? false: true
      }, ()=> { 
        let text = this.props.homeWork.getIn([idx,'answer', 'text']) ? this.props.homeWork.getIn([idx,'answer', 'text']) : ''
        window.editor2.txt.html(text); 
      })
    } else {
      message.success('恭喜您已经完成了所有的练习！')
      setTimeout(()=> {
        this.setState({
          answerVisible: false,
          count: 0,
          next: false,
          answer: {
            text: '',
            img: ''
          }
        })
      },2000)
    }
  }

  changeAnswer() {
    let idx = this.state.count 
    // this.props.getHome({
    //   lessonId: this.props.video.get('lessonId'),
    //   period: this.props.video.get('period')
    // })

    api.getHomeWorks({
      lessonId: this.props.video.get('lessonId'),
      period: this.props.video.get('period')
    }).then(res => {
      if(res.code === 20000) {
        // dispatch(changeWorkHome(res.data))

        this.props.changeWorkHome(res.data)
        this.setState({answerVisible: true,count: 0, next:(idx+1)< this.props.homeWork.size ? true: false, answer: {text: this.props.homeWork.getIn([idx,'answer','text']), img: this.props.homeWork.getIn([idx,'answer','picUrl'])} }, ()=> {
          if(!this.state.initEdit) {
            setTimeout(()=> {
              var E = require('wangeditor')
              window.editor2 = new E('#answer-edit')
              window.editor2.create()
              window.editor2.txt.html(this.props.homeWork.getIn([idx,'answer','text']))
              this.setState({
                initEdit: true
              })
            },300)
          }else {
            window.editor2.txt.html(this.props.homeWork.getIn([idx,'answer','text']))
          }
        })
      }
    })
  }

  // 获取url参数
  getQueryStr(name)
  {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); 
      var r = this.props.location.search.substr(1).match(reg);
      if (r != null && r != undefined) {
        return unescape(r[2]);
      }
      return null;
  }

  renderPay() {
    if(!document.getElementById('liveVideo') && !document.getElementById('liveVideoNormal')) {
      return 
    }
    if(window.myVideo) {
      window.myVideo.dispose()
    }

    let uid = this.props.video.get('type')=== 'JoyActivity' ? 'liveVideo' : 'localVideo'
    
    if(this.state.normal) {
      window.myVideo = window.videojs(uid, {
        bigPlayButton: true,
        textTrackDisplay: false,
        posterImage: false,
        errorDisplay: false,
      })
    }else {
      window.myVideo = window.videojs('liveVideoNormal', {
        bigPlayButton: true,
        textTrackDisplay: false,
        posterImage: false,
        errorDisplay: false,
      })
    }
    window.myVideo.play()

    var videoPanelMenu = $('.vjs-fullscreen-control')
    videoPanelMenu.before('<div class="vjs-subs-caps-button  vjs-menu-button vjs-menu-button-popup vjs-control vjs-button"  aria-live="polite" aria-expanded="false" aria-haspopup="true">'  
        + '<div class="vjs-menu" role="presentation">'  
        + '<ul class="vjs-menu-content" role="menu">'  
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="1"  οnclick="changeVideo(1)">流畅</li>'  
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="2" οnclick="changeVideo(2)">标清</li>'  
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="3" οnclick="changeVideo(3)">高清</li>'
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="3" οnclick="changeVideo(4)">超清</li>'    
        + '</ul></div>'  
        +'  <button class="vjs-subs-caps-button vjs-control vjs-button" type="button" aria-live="polite" title="清晰度切换" aria-disabled="false">'  
        +'      <span aria-hidden="true" class="vjs-icon-placeholder"></span><span class="vjs-control-text">清晰度切换</span>'  
        +'  </button>'  
        +'</div>'  
    );

    $('.vjs-menu-item').on('click', (e)=> {
      let status = e.target.getAttribute('type')
      // var ctime= window.videojs.currentTime();  
      let src = ''
      let type = this.props.video.get('type') === 'JoyActivity' ? 'application/x-mpegURL' : 'video/mp4'
      switch(status) {
        case '1':
          src = this.props.video.get('m3u8_lld_url')
          break;
        case '2':
          src = this.props.video.get('m3u8_lsd_url')
          // window.videojs("liveVideo").src([{type: "application/x-mpegURL", src: this.props.video.get('m3u8_lsd_url')}]);  
          // window.videojs("liveVideo").play();  
          break;
        case '3':
          src = this.props.video.get('m3u8_lhd_url')
          // window.videojs("liveVideo").src([{type: "application/x-mpegURL", src: this.props.video.get('m3u8_lhd_url')}]);  
          // window.videojs("liveVideo").play(); 
          break;
        case '4':
          src = this.props.video.get('m3u8_lud_url')
          // window.videojs("liveVideo").src([{type: "application/x-mpegURL", src: this.props.video.get('m3u8_lud_url')}]);  
          // window.videojs("liveVideo").play(); 
          break;
      }
      window.myVideo.reset()
      window.myVideo.src({type, src})
      window.myVideo.load(src);
      window.myVideo.play()
      // window.myVideo.on('loadedmetadata', function() {
      //   window.localVideo.play()
      //   window.localVideo.currentTime(ctime)
      // })
      // window.videojs("liveVideo").src([{type: "application/x-mpegURL", src: src}]);  
      // window.videojs("liveVideo").play(); 
    })
  }

  initWebSocket() {
    if ("WebSocket" in window) {
      // alert("您的浏览器支持 WebSocket!");
      // 打开一个 web socket
      let userId = JSON.parse(localStorage.getItem('userData')).id
      window.websock = new WebSocket(
        "wss://api.0574edu.net/websocket/"+ this.getQueryStr('roomId') + "/" + userId
        // "wss://api.test.joylive.86edu.net/websocket/"+ this.getQueryStr('roomId') + "/" + userId
      );

      window.websock.onopen = this.websocketonopen;
      window.websock.onerror = this.websocketonerror;
      window.websock.onmessage = this.websocketonmessage.bind(this);
      window.websock.onclose = this.websocketclose;
    } else {
      // 浏览器不支持 WebSocket
      alert("您的浏览器不支持 WebSocket!");
    }
  }
  websocketonopen() {
    console.log('连接成功!')
  }
  websocketonerror(e) {
    console.log("WebSocket连接发生错误");
  }
  websocketclose() {
    console.log('连接关闭!')
    // this.initWebSocket()
    window.websock = null
    // this.initWebSocket()
  }

  getAllComment(obj) {
    this.setState({
      page: obj.page,
      pageSize: obj.pageSize
    }, ()=> this.props.getComment(obj))
  }
  // 数据接收
  websocketonmessage(etc) {
    console.log('etc', etc)
    let arr = this.state.chatList ? this.state.chatList : []
    let result = JSON.parse(etc.data)
    if (result.messageType ===1) {
      arr.push({
        username: result.username,
        status: "online",
        message: "已上线",
        isAll:  true
      })
    }else if(result.messageType === 2) {
    }else if(result.messageType === 3) {
      this.setState({
        onlineList: result.onlineUsers
      })
      // this.onlineList = result.onlineUsers
    } else if(result.messageType ===4){
      arr.push({
        username: result.fromusername,
        status: "message",
        message: result.textMessage,
        to: result.tousername,
        isAll:  result.tousername === '所有人' ? true : false
      })
    } else if(result.messageType ===5) {
        arr.push({
        username: result.fromusername,
        status: "system",
        message: result.textMessage,
        to: result.tousername,
        isAll:  result.tousername === '所有人' ? true : false
      })
    } else if(result.messageType ===6) {
      this.setState({
        url: result.url
      })
    }else if(result.messageType === 7) {
      let obj = {}
      obj.page = this.state.page
      obj.pageSize = this.state.pageSize
      if(this.props.video.get('type') === 'JoyActivity') {
        obj.actId = this.props.video.get('actId')
      }else {
        obj.videoId = this.props.video.get('videoId')
      }
      this.props.getComment(obj)
    }

    this.setState({
      chatList: arr
    })
  }
  // 数据发送
　websocketsend(){//数据发送
    if(this.state.chat) {
      let message = {
        "message":this.state.chat,
        "username": this.state.userData.name+ '_' + this.state.userData.id,
        "to": "All"
      };
      window.websock.send(JSON.stringify(message));
      this.setState({
        chat: ''
      })
    }else {
      message.error('您未输入任何内容')
    }
　}

  onChange(info) {
    if (info.file.status !== 'uploading') {
      if(info.file.response.code === 20000) {
        let obj = this.state.answer
        obj.img = info.file.response.data
        this.setState({
          answer: obj
        })
      }
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }

  cancelTip() {

  }

  renderbtn() {
    let arr = []
    let idx = this.state.count
    if(this.props.homeWork.getIn([idx,'answer'])) {
      arr = [<Popconfirm
        title="您已经提交过答案,再次提交会覆盖答案,是否继续?"
        onConfirm={this.handleAnswer.bind(this)}
        onCancel={this.cancelTip.bind(this)}
        okText="是"
        cancelText="否"
      >
        <Button type="primary">提交答案</Button>
      </Popconfirm>]
    }else {
      arr = [<Button type="primary" onClick={this.handleAnswer.bind(this)}>提交答案</Button>]
    }

    // if(this.state.next) {
    //   arr.push(<Button onClick={()=> this.nextWork()}>下一题</Button>)
    // }
    return arr
  }

  renderContent() {
    if(this.props.video) {
      if(this.props.video.get('type') === 'JoyActivity') {
        return this.renderLive()
      }else if(this.props.video.get('type') === 'LocalVideo'){
        return <Video {...this.props} changeVisible={()=> this.setState({visible: true})}  changeAnswer={this.changeAnswer.bind(this)} renderHeader={this.renderHeader}/>
      }
    }
  }

  render() {
    const idx = this.state.count
    const props = {
      name: 'file',
      withCredentials: true,
      action: 'https://api.0574edu.net/user/upload/img'
      // action: 'http://api.test.joylive.86edu.net/user/upload/img'
    }
    return (
      <div>
        {
          this.renderContent()
        }
        <Modal
          title="评分"
          visible={this.state.visible}
          onOk={this.handleRate.bind(this)}
          cancelText="取消"
          centered={true}
          okText="确定"
          onCancel={this.handleCancel.bind(this)}
        >
          <p>听完了，觉得老师说的怎么样，快来打分吧</p>
          <Rate allowHalf onChange={(val)=> this.setState({rateValue: val})}/>
        </Modal>
        <Modal
          title={'练习' + (idx + 1) + '/' + this.props.homeWork.size}
          visible={this.state.answerVisible}
          centered={true}
          okText="提交答案"
          width="1000"
          onCancel={this.handleCancel.bind(this)}
          footer={this.renderbtn()}
        >
          <div>
            {/* {renderContent(this.props.homeWork.getIn([idx, 'homework']))} */}
            {
              this.props.homeWork ? (
            this.props.homeWork.getIn([idx,'homework', 'type']) === 0 ? <div dangerouslySetInnerHTML={{__html: this.props.homeWork.getIn([idx, 'homework', 'text'])}}></div> : <img alt="" style={{maxWidth: '100%'}} src={this.props.homeWork.getIn([idx, 'homework', 'text'])} />
              ): ''
            }
          </div>
          <div id="answer-edit" style={{width: '1000px'}}> 

          </div>
          <Upload {...props} onChange={this.onChange.bind(this)} accept=".jpg, .jpeg, .png" ref='upload' key={Math.random()}> 
            <Button>
              <Icon type="upload" /> 上传图片
            </Button>
          </Upload>
          {
            this.state.answer.img ?  <span>{this.state.answer.img} <a onClick={()=> this.setState({
              answer: {
                img: '',
                text: this.state.answer.text
              }
            })}>删除图片</a></span> : ''
          }
          {
            this.props.homeWork.getIn([idx,'answer']) ? <div style={{marginTop: '20px'}}>
            <p style={{height: '30px', backgroundColor: '#f0f0f0', lineHeight: '30px',textAlign:'center'}}>我的回答</p>
            <div>
              <div dangerouslySetInnerHTML={{__html: this.props.homeWork.getIn([idx,'answer', 'text'])}}></div>
              <img alt="" style={{maxWidth: '100%'}} src={this.props.homeWork.getIn([idx,'answer', 'picUrl'])} />
            </div>
          </div> : ''
          }

        </Modal>
      </div>
    )
  }
}

const mapStatus = (status) => {
  return {
    video: status.getIn(['live', 'live']),
    rate: status.getIn(['live', 'rate']),
    comment: status.getIn(['live', 'comment']),
    liveImg: status.getIn(['live','liveImg']),
    localImg: status.getIn(['live', 'localImg']),
    homeWork: status.getIn(['live', 'homeWork']),
    downUrl: status.getIn(['live', 'url'])
  }
}

const mapDispatch = (dispatch) => {
  return {
    getVideoItem(params) {
      dispatch(actionCreators.getVideoItem(params))
    },
    addRate(params) {
      dispatch(actionCreators.addRate(params))
    },
    addComment(params) {
      dispatch(actionCreators.addComment(params))
    },
    reply(params) {
      dispatch(actionCreators.reply(params))
    },
    getComment(params) {
      dispatch(actionCreators.getComment(params))
    },
    saveHomeWork(params) {
      dispatch(actionCreators.saveHomeWork(params))
    },
    getHome(params) {
      dispatch(actionCreators.getHomeWork(params))
    },
    changeWorkHome(params) {
      dispatch(actionCreators.changeWorkHome(params))
    }
  }
}


export default connect(mapStatus, mapDispatch)(withRouter(Live))